package main

import (
	"errors"
	"fmt"
	"os"
)

type CircleQueue struct {
	maxSize int
	array   [5]int
	head    int
	tail    int
}

// 数组模拟环形链表，实际容量为size-1
func main() {
	queue := &CircleQueue{
		maxSize: 5,
		head:    0,
		tail:    0,
	}
	var key string
	var val int
	for {
		fmt.Println("1 输入add 表示添加数据到队列")
		fmt.Println("2 输入get 表示添从队列取数据")
		fmt.Println("3 输入show 表示显示队列")
		fmt.Println("4 输入exit 表示退出")

		fmt.Scanln(&key)

		switch key {
		case "add":
			fmt.Println("输入要入队列的数字")
			fmt.Scanln(&val)
			err := queue.Push(val)
			if err != nil {
				fmt.Println("加入队列错误：", err)
			} else {
				fmt.Println("加入队列成功")
			}
		case "get":
			data, err := queue.Pop()
			if err != nil {
				fmt.Println(err)
			} else {
				fmt.Println(data)
			}
		case "show":
			queue.ShowQueue()
		case "exit":
			os.Exit(0)
		default:
			fmt.Println("输入错误")
		}

	}
}
func (this *CircleQueue) IsFull() bool {
	return (this.tail+1)%(this.maxSize) == this.head
}
func (this *CircleQueue) IsEmpty() bool {
	return this.tail == this.head
}
func (this *CircleQueue) Size() int {
	return (this.tail + this.maxSize - this.head) % this.maxSize
}

func (this *CircleQueue) Push(val int) (err error) {
	if this.IsFull() {
		return errors.New("queue full")
	}
	this.array[this.tail] = val // 值给尾部
	this.tail = (this.tail + 1) % this.maxSize
	return
}

func (this *CircleQueue) Pop() (val int, err error) {
	if this.IsEmpty() {
		return -1, errors.New("queue empty")
	}

	val = this.array[this.head]
	this.head = (this.head + 1) % this.maxSize
	return val, err
}

func (this *CircleQueue) ShowQueue() {
	size := this.Size()
	if size == 0 {
		fmt.Println("queue is empty")
		return
	}
	tempHead := this.head
	for i := 0; i <= size; i++ {
		fmt.Printf("array[%d]=%d \t \n", i, this.array[tempHead])
		tempHead = (tempHead + 1) % this.maxSize
	}
}
